package com.middlegroup.pay.config;

import com.middlegroup.common.exception.BusinessException;
import com.middlegroup.common.model.ResponseEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.servlet.http.HttpServletResponse;

/**
 * ClassName:GrobalExceptionHandler <br/>
 *
 * @author pc
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Throwable.class)
    @ResponseBody
    public ResponseEntity jsonErrorHandler(Exception e, HttpServletResponse rep) throws Exception {
        log.error("出错啦", e);
        String msg = "系统出错，请联系管理员!";
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
            rep.setStatus(400);
            return new com.middlegroup.common.model.ResponseEntity(com.middlegroup.common.model.ResponseEntity.STATUS_FAIL,null,msg,null);
        } else if (e instanceof BusinessException) {
            BusinessException exception = (BusinessException) e;
            //rep.setStatus(exception.getCode());
            return new ResponseEntity(ResponseEntity.STATUS_OK,null,exception.getMessage(),null);
        } else if (e instanceof IllegalArgumentException) {
            IllegalArgumentException exception = (IllegalArgumentException) e;
            //rep.setStatus(HttpStatus.BAD_REQUEST.value());
            return new ResponseEntity(ResponseEntity.STATUS_OK,null,exception.getMessage(),null);
        } else if (e instanceof MultipartException) {
            //rep.setStatus(HttpStatus.BAD_REQUEST.value());
            return new ResponseEntity(ResponseEntity.STATUS_OK,null,"图片大小不能超过3M",null);
        }else if (e instanceof BindException){
            BindException bindException = (BindException) e;
            StringBuffer sb  = new StringBuffer();
            for (FieldError fieldErro : bindException.getBindingResult().getFieldErrors()) {
                sb.append("【" + fieldErro.getField() + ":" + fieldErro.getDefaultMessage() + "】") ;
            }
            msg = sb.toString();
            return new ResponseEntity(ResponseEntity.STATUS_FAIL,null,msg,null);
        }
        return new ResponseEntity(ResponseEntity.STATUS_OK,null,msg,null);
    }

   /* *//**
     * 通用的接口映射异常处理方法
     *//*
    @Override
    protected org.springframework.http.ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers,
                                                                                      HttpStatus status, WebRequest request) {
        logger.error("出错啦", ex);
        if (ex instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) ex;
            return new org.springframework.http.ResponseEntity<>(exception.getBindingResult().getAllErrors().get(0).getDefaultMessage(), status);
        }
        if (ex instanceof MethodArgumentTypeMismatchException) {
            MethodArgumentTypeMismatchException exception = (MethodArgumentTypeMismatchException) ex;
            logger.error("参数转换失败，方法：" + exception.getParameter().getMethod().getName() + "，参数：" + exception.getName()
                    + ",信息：" + exception.getLocalizedMessage());
            return new org.springframework.http.ResponseEntity<>("参数转换失败", status);
        }
        if (ex instanceof NoHandlerFoundException){
            return new org.springframework.http.ResponseEntity<>(" No handler found", status);
        }
        if (ex instanceof BindException){
            ex.printStackTrace();
        }
        return new org.springframework.http.ResponseEntity<>("参数转换失败", status);
    }*/
}
